package com.zhanghu.backendZray.service.impl;

import com.alibaba.fastjson.JSON;
import com.zhanghu.backendZray.service.RocksDBService;
import org.rocksdb.RocksDB;
import org.rocksdb.RocksDBException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Objects;

@Service
public class RocksDBServiceImpl implements RocksDBService {

    @Resource
    private RocksDB rocksDB;

    public void putData(Object key, Object value) throws RocksDBException {
        rocksDB.put(Objects.toString(key).getBytes(), JSON.toJSONString(value).getBytes());
    }

    public <T> T getData(Object key, Class<T> clazz) throws RocksDBException {
        byte[] valueBytes = rocksDB.get(Objects.toString(key).getBytes());
        return valueBytes != null ? JSON.parseObject(new String(valueBytes), clazz) : null;
    }

    public void updateData(Object key, Object value) throws RocksDBException {
        rocksDB.put(Objects.toString(key).getBytes(), JSON.toJSONString(value).getBytes());
    }

    public void deleteData(Object key) throws RocksDBException {
        rocksDB.delete(Objects.toString(key).getBytes());
    }
}
